<template>
  <div>
    <slot v-if="!hasError"></slot>
    <div v-else class="error-boundary">
      <div class="error-boundary-content">
        <el-icon class="error-icon"><Warning /></el-icon>
        <p class="error-message">错误处理组件出现异常</p>
        <el-button @click="retry" size="small" type="primary">重试</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onErrorCaptured } from 'vue';
  import { Warning } from '@element-plus/icons-vue';

  const hasError = ref(false);
  const errorInfo = ref<any>(null);

  // 捕获子组件错误
  onErrorCaptured((error, instance, info) => {
    console.error('ErrorBoundary captured error:', error, info);
    hasError.value = true;
    errorInfo.value = { error, instance, info };

    // 返回 false 阻止错误向上传播
    return false;
  });

  // 重试功能
  const retry = () => {
    hasError.value = false;
    errorInfo.value = null;

    // 给组件一点时间重新渲染
    setTimeout(() => {
      if (hasError.value) {
        console.warn('Component still has error after retry');
      }
    }, 1000);
  };
</script>

<style lang="scss" scoped>
  .error-boundary {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background: #fff;
    border: 1px solid #f56c6c;
    border-radius: 4px;
    padding: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    z-index: 9999;
    max-width: 300px;
  }

  .error-boundary-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    gap: 12px;
  }

  .error-icon {
    font-size: 24px;
    color: #f56c6c;
  }

  .error-message {
    margin: 0;
    font-size: 14px;
    color: #606266;
  }
</style>
